import SpacingMarker from '.';
import { RectAttr } from './type';

export default class Rect {
  top: number;
  bottom: number;
  left: number;
  right: number;
  width: number;
  height: number;

  constructor(rect: RectAttr) {
    this.top = rect.top;
    this.bottom = rect.bottom;
    this.left = rect.left;
    this.right = rect.right;
    this.width = rect.width;
    this.height = rect.height;
  }
  // 与other碰撞
  colliding(other: Rect) {
    return !(this.top > other.bottom || this.right < other.left || this.bottom < other.top || this.left > other.right);
  }
  // 把other包含
  containing(other: Rect) {
    return this.top <= other.top && this.right >= other.right && this.bottom >= other.bottom && this.left <= other.left;
  }
  // 在other内部
  inside(other: Rect) {
    return this.top >= other.top && this.right <= other.right && this.bottom <= other.bottom && this.left >= other.left;
  }
}

export function getRect(element: HTMLElement): RectAttr {
  if (SpacingMarker.getRect) return SpacingMarker.getRect(element);
  if (SpacingMarker.useBoundingClientRect || SpacingMarker.el === document.body) return element.getBoundingClientRect();
  const getAttr = (name: string) => Number(element.getAttribute(name));
  const left = element.offsetLeft || getAttr('x');
  const top = element.offsetTop || getAttr('y');
  const width = element.scrollWidth || getAttr('width');
  const height = element.scrollHeight || getAttr('height');
  return {
    top: top,
    bottom: top + height,
    left: left,
    right: left + width,
    width: width,
    height: height,
  };
}
